<template>
  <div>
    <div class="business-content-wrap">
      <!-- 左侧列表区域 -->
      <div
        class="left-box"
        :class="{ fullWidth: currentOrderId && selectedOrderData.pay_status === 1 ? false : true }"
      >
        <div class="left-box-title">营业账单</div>

        <!-- 搜索区 -->
        <div class="search-box-wrap">
          <div class="time-pay-box">
            <div class="betweenTime-box">
              <el-date-picker
                v-model="dateRangeList"
                type="daterange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD"
                @change="onSearch"
              />
            </div>
            <div class="payMethod-box">
              <span class="payMethod-text">支付方式</span>
              <el-select
                v-model="searchParam.payMethod"
                @change="onSearch"
                class="select"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in payMethodList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </div>

          <div class="search-box">
            <div class="search-input-box">
              <img class="search-icon" src="@/assets/images/home/search-icon.png" alt="" />
              <input
                class="input"
                v-model.trim="pageListQuery.search"
                type="text"
                placeholder="搜索桌台/开台人/收银员"
                @input="onSearch"
              />
            </div>
          </div>
        </div>

        <!-- 状态筛选 -->
        <div class="search-btn-group">
          <span class="all" :class="activeIndex === 0 ? 'active' : ''" @click="handleActive(0)"
            >全部</span
          >
          <span class="closed" :class="activeIndex === 1 ? 'active' : ''" @click="handleActive(1)"
            >已结账</span
          >
          <span class="unclosed" :class="activeIndex === 2 ? 'active' : ''" @click="handleActive(2)"
            >未结账</span
          >
        </div>

        <!-- 表格 -->
        <div
          class="table-wrap"
          :class="{
            fullWidth: currentOrderId && selectedOrderData.pay_status === 1 ? false : true
          }"
          v-loading="tableLoading"
          element-loading-text="加载中..."
        >
          <el-table
            :data="tableData"
            border
            @row-click="singleElection"
            :height="tableHeight"
            table-layout="fixed"
          >
            <el-table-column align="center" width="50">
              <template #default="scope">
                <el-radio v-model="templateSelection" :label="scope.row.id">&nbsp;</el-radio>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip align="center" prop="id" label="账单编号" />
            <el-table-column show-overflow-tooltip align="center" prop="desk_name" label="桌台" />
            <el-table-column
              show-overflow-tooltip
              align="center"
              prop="open_clerk_name"
              label="开台人"
            />
            <el-table-column
              show-overflow-tooltip
              align="center"
              prop="end_clerk_name"
              label="收银员"
            />
            <el-table-column
              show-overflow-tooltip
              align="center"
              prop="create_time"
              label="开台时间"
            />
            <el-table-column
              show-overflow-tooltip
              align="center"
              prop="pay_time"
              label="结束时间"
            />
            <el-table-column
              show-overflow-tooltip
              align="center"
              prop="model_money"
              label="应收金额(元)"
            />
            <el-table-column
              show-overflow-tooltip
              align="center"
              prop="total_discount_money"
              label="优惠金额(元)"
            />
            <el-table-column
              show-overflow-tooltip
              align="center"
              prop="real_pay_money"
              label="实收金额(元)"
            />
            <el-table-column show-overflow-tooltip align="center" label="支付方式">
              <template #default="scope">
                <div>{{ scope.row.pay_type }}</div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="table-total" v-show="pageListTotal > 0">
          <span>共{{ pageListTotal }}条</span>
          <div>
            <Pagination
              v-show="pageListTotal > 0"
              :total="pageListTotal"
              v-model:page="pageListQuery.page"
              v-model:limit="pageListQuery.limit"
              @pagination="getDeskOrderList"
              :pageSizes="[15, 30, 45, 100]"
            />
          </div>
        </div>

        <!-- 底部按钮 -->
        <div class="data-summary-box">
          <span class="summary-text"></span>
          <div class="sumary-btn-group">
            <el-button class="create-dishes" @click="handleAction(0)" :loading="createLoading"
              >生成菜谱</el-button
            >
            <el-button class="print" @click="handleReprint" :loading="reprintLoading"
              >重新打印</el-button
            >
            <el-button
              class="cancel-closing"
              type="danger"
              plain
              @click="openOrderCancelDialog"
              :disabled="!currentOrderId"
              >反结账</el-button
            >
            <el-button class="cancel" @click="handleAction(3)">返回</el-button>
          </div>
        </div>
      </div>

      <!-- 右侧详情区域 -->
      <div class="right-box" v-if="selectedOrderData.pay_status === 1">
        <BusinessBillCard :selectedOrderId="currentOrderId" :activeIndex="activeIndex" />
      </div>
      <!-- 反结账弹窗集成 -->
      <OrderCancelDialog
        v-model="showOrderCancelDialog"
        :orderId="currentOrderId"
        :orderNo="selectedOrderData?.id"
        @confirm-success="getDeskOrderList"
      />
      <!-- 生成菜谱弹窗集成 -->
      <CreateDishes v-model:createVisible="isShowCreate" :orderId="currentOrderId" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import OrderCancelDialog from './components/OrderCancelDialog/Index.vue'
import CreateDishes from './components/CreateDishes/Index.vue'
import BusinessBillCard from './components/BusinessBillCard/Index.vue'
import Pagination from '@/components/Pagination/Index.vue'
import { deskOrderList, printOrderReprint } from '@/api/statistics'
import { fetchTicketDetail } from '@/api/user'
import { debounce } from '@/utils/toolsValidate'
import { ElMessage } from 'element-plus'

const searchParam = ref({ payMethod: '' })
const payMethodList = ref([
  { label: '全部', value: '' },
  { label: '微信支付', value: 'wechat' },
  { label: '支付宝', value: 'alipay' },
  { label: '余额', value: 'balance' },
  { label: '现金', value: 'cash' },
  { label: '挂账', value: 'on_account' },
  { label: '虚收', value: 'virtual' },
  { label: '积分', value: 'integripay' }
])

const activeIndex = ref(0)
const isShowCreate = ref(false)
const tableData = ref<any[]>([])
const pageListQuery = ref({
  page: 1,
  limit: 15,
  betweenTime: null as any,
  search: null as any,
  pay_status: -1
})
const pageListTotal = ref(0)
const currentOrderId = ref('')
const selectedOrderData = ref<any>({ pay_status: '' })
const dateRangeList = ref<any[]>([])
const templateSelection = ref('')
// 固定表格高度，内部滚动，避免页面超出（老项目约 576px）
const tableHeight = 376
// 底部操作按钮 loading
const createLoading = ref(false)
const reprintLoading = ref(false)
const cancelLoading = ref(false)
const showOrderCancelDialog = ref(false)
const tableLoading = ref(false)

const onSearch = debounce((val?: any) => {
  if (dateRangeList.value.length > 0) {
    pageListQuery.value.betweenTime = [
      dateRangeList.value[0] + ' 00:00:00',
      dateRangeList.value[1] + ' 23:59:59'
    ]
  } else {
    pageListQuery.value.betweenTime = null as any
  }
  pageListQuery.value.page = 1
  getDeskOrderList()
}, 500)

async function getDeskOrderList() {
  try {
    tableLoading.value = true
    const res = await deskOrderList({
      ...pageListQuery.value,
      pay_method: searchParam.value.payMethod
    })
    if (res.status === 200) {
      tableData.value = res?.data?.list?.data || []
      pageListTotal.value = res?.data?.list?.total || 0
    }
  } catch (error) {
    console.error('获取营业账单列表失败:', error)
  } finally {
    tableLoading.value = false
  }
}

function handleActive(index: number) {
  currentOrderId.value = ''
  activeIndex.value = index
  const ACTIVE_MAP: Record<number, number> = { 0: -1, 1: 1, 2: 3 }
  pageListQuery.value.pay_status = ACTIVE_MAP[index]
  getDeskOrderList()
}

function singleElection(row: any) {
  selectedOrderData.value = row
  currentOrderId.value = String(row.id)
  templateSelection.value = row.id
}

function handleAction(index: number) {
  if ([0, 1, 2].includes(index) && !currentOrderId.value) {
    ElMessage.error('请先选择订单')
    return
  }
  if (index === 3) {
    history.go(-1)
    return
  }
  if (index === 0) {
    isShowCreate.value = true
    return
  }
}

async function handleReprint() {
  if (!currentOrderId.value) {
    ElMessage.error('请先选择订单')
    return
  }
  if (selectedOrderData.value.pay_status !== 1) {
    ElMessage.error('当前订单未支付，不能进行打印操作')
    return
  }
  try {
    reprintLoading.value = true
    // 获取小票详情以获取 ticket_id
    const res = await fetchTicketDetail({
      order_id: currentOrderId.value,
      type: 'JZ'
    })
    if (res.status === 200 && res?.data?.detail?.ticket_id) {
      await printOrderReprint({ ticket_id: res.data.detail.ticket_id })
      ElMessage.success('推送打印成功')
    } else {
      ElMessage.error('获取小票信息失败')
    }
  } catch (error) {
    console.error('打印失败:', error)
    ElMessage.error('打印失败')
  } finally {
    reprintLoading.value = false
  }
}

function openOrderCancelDialog() {
  if (!currentOrderId.value) {
    ElMessage.error('请先选择订单')
    return
  }
  showOrderCancelDialog.value = true
}

getDeskOrderList()
</script>

<style scoped lang="scss">
.business-content-wrap {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.left-box {
  box-sizing: border-box;
  background: #ffffff;
  border-radius: 20px;
  box-shadow: 3px 0px 24px 0px rgba(0, 0, 0, 0.16);
  display: flex;
  align-items: flex-start;
  flex-direction: column;
  width: calc(100% - 440px); // 当右侧存在时的宽度
  min-height: calc(100vh - 120px);
}

.fullWidth {
  width: 100% !important; // 当右侧不存在时占满
}

.left-box-title {
  width: 100%;
  overflow-x: hidden;
  box-sizing: border-box;
  height: 88px !important;
  background: #f4f4f4;
  border-radius: 20px 20px 0px 0px;
  font-size: 20px;
  font-weight: 700;
  color: #333333;
  display: flex;
  justify-content: center;
  align-items: center;
}

.search-box-wrap {
  margin-top: 20px;
  padding: 10px 30px;
  width: 100%;
  overflow: hidden;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.time-pay-box {
  display: flex;
  align-items: center;
  gap: 20px;
}
.betweenTime-box .betweenTime-text {
  font-size: 16px;
  color: #333;
  margin: 20px;
}
.betweenTime-box :deep(.el-date-editor) {
  min-width: 360px;
}
.payMethod-box {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-left: 0;
}
.payMethod-text {
  font-size: 16px;
  color: #333;
  margin-right: 0;
  white-space: nowrap;
}
.select {
  width: 280px;
}

.search-box {
  display: flex;
  justify-content: flex-end;
}
.search-input-box {
  width: 280px;
  height: 40px;
  border: 1px solid #d2d2d2;
  border-radius: 25px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  padding-left: 10px;
}
.search-icon {
  width: 24px;
  height: 24px;
}
.search-input-box .input {
  border: none;
  outline: none;
  width: 200px;
  font-size: 14px;
  color: #333;
  margin-left: 6px;
}

.search-btn-group {
  margin-top: 20px;
  display: flex;
  padding-left: 36px;
  .active {
    border: 1px solid #7c0a03 !important;
    color: #7c0a03 !important;
  }
}
.search-btn-group .all,
.search-btn-group .closed,
.search-btn-group .unclosed {
  width: 116px;
  height: 40px;
  background: #ffffff;
  border-radius: 12px;
  font-size: 16px;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #d2d2d2;
  cursor: pointer;
}
.search-btn-group .all,
.search-btn-group .closed {
  margin-right: 24px;
}

.table-wrap {
  box-sizing: border-box;
  padding: 20px 30px 30px 30px;
  width: 100%;
}
/* 使用 el-table 的 :max-height 控制滚动 */

.table-total {
  font-size: 14px;
  color: #333333;
  padding: 0 30px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 10px;
  width: 100%;
  box-sizing: border-box;
}

.data-summary-box {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px 30px;
  box-sizing: border-box;
  .summary-text {
    font-size: 14px;
    color: #30314a;
  }
  .sumary-btn-group {
    display: flex;
    align-items: center;
  }
  .sumary-btn-group .create-dishes,
  .sumary-btn-group .print,
  .sumary-btn-group .cancel-closing,
  .sumary-btn-group .cancel {
    min-width: 140px;
    height: 52px;
    background: #ffffff;
    border: 1px solid #333333;
    border-radius: 12px;
    font-size: 18px;
    color: #333333;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
  }
  .sumary-btn-group .print {
    margin-left: 40px;
  }
  .sumary-btn-group .cancel-closing {
    margin-left: 40px;
  }
  .sumary-btn-group .cancel {
    margin-left: 40px;
  }
}

.right-box {
  width: 420px;
  background: #fff;
  border-radius: 20px;
  //   padding: 16px;
}
.placeholder-card {
  height: 100%;
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}

@media (max-width: 1600px) {
  .left-box {
    width: calc(100% - 420px);
  }
}
// @media (max-width: 1400px) {
//   .left-box {
//     width: 100%;
//   }
//   .right-box {
//     display: none;
//   }
// }
</style>
